<template>
  <a-modal :visible="visible" width="65vw" title="选择车型" @cancel="close" unmount-on-close>
    <list-searcher :searchList="searchList" v-model:searchForm="carModelStockState.queryParam" columns="2" @loadData="loadData" />
    <!-- 骨架屏 -->
    <a-skeleton v-if="initLoading" :animation="true">
      <a-skeleton-line :rows="5" :line-height="90" />
    </a-skeleton>
    <a-spin v-else :loading="listLoading" tip="加载中...">
      <StockBody isModal @loadData="loadData" />
    </a-spin>
    <!-- 底部 -->
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="onSubmit" :loading="loading">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts" name="carModelSelector">
  import { ref, reactive, computed, provide, h } from 'vue'
  import { Modal, Message } from '@arco-design/web-vue'
  import { getCarModelStock } from '@/api/asset/carModelStock'
  import StockBody from './car-model/components/stock-body.vue'
  import dayjs from 'dayjs'

  const visible = ref(false)
  const close = () => {
    visible.value = false
  }
  let orderInfo = {
    startTime: '',
    endTime: '',
    siteId: '',
    modelId: '',
  }
  const open = (queryParam: any) => {
    visible.value = true
    orderInfo = {
      startTime: queryParam.dateRange[0],
      endTime: queryParam.dateRange[1],
      siteId: queryParam.siteId,
      modelId: '',
    }
    // 初始化参数
    const modelId = queryParam.modelId
    carModelStockState.selector.id = modelId
    // 由于list-searcher车型改为多选，清空并转为modelIdList数组
    queryParam.modelId = undefined
    carModelStockState.selector.id = modelId
    if (modelId) {
      queryParam.modelIdList = [modelId + '']
    }
    carModelStockState.queryParam = queryParam
    loadData()
  }
  defineExpose({
    open,
  })

  const carModelStockState = reactive({
    stockData: [],
    statistics: {},
    // 接口参数（不包含page信息）
    queryParam: {
      siteId: undefined,
      seriesIdList: undefined,
      modelIdList: undefined,
      // 取值订单租赁周期
      dateRange: [],
      startTime: '',
      endTime: '',
    },
    selector: {
      id: '',
      carModel: {
        useNum: 0,
        stockNum: 0,
      },
    },
  })
  provide('carModelStockState', carModelStockState)

  // 查询条件
  const searchList = computed(() => {
    return [
      {
        label: '门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_listBystaff',
          params: { oldId: orderInfo.siteId },
          disabled: true,
        },
        // 变更门店，车系车型清空
        change: () => {
          carModelStockState.queryParam.seriesIdList = undefined
          carModelStockState.queryParam.modelIdList = undefined
        },
      },
      {
        label: '车系',
        prop: 'seriesIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_carSeries_bySite',
          params: {
            siteId: carModelStockState.queryParam.siteId,
          },
          // 变更，车型清空
          change: () => {
            carModelStockState.queryParam.modelIdList = undefined
          },
        },
      },
      {
        label: '车型',
        prop: 'modelIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_car_model_bySite',
          params: {
            siteId: carModelStockState.queryParam.siteId,
            seriesIdList: carModelStockState.queryParam.seriesIdList,
          },
        },
      },
      {
        label: '时间',
        prop: 'dateRange',
        span: 2,
        type: 'i-range-picker',
        attrs: {
          allowClear: false,
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
      },
    ]
  })

  // 确认
  const emit = defineEmits(['confirm'])
  const onSubmit = () => {
    if (!carModelStockState.selector.id) {
      Message.warning('请选择车型')
      return
    }
    confirmUseCarModel()
  }
  // 获取车型使用信息
  const loading = ref(false)
  const confirmUseCarModel = () => {
    loading.value = true
    const query = { ...orderInfo }
    query.modelId = carModelStockState.selector.id
    query.startTime = dayjs(query.startTime).format('YYYY-MM-DD 00:00:00')
    query.endTime = dayjs(query.endTime).format('YYYY-MM-DD 23:59:59')

    getCarModelStock(query).then((res: any) => {
      loading.value = false
      const list = res.result.list
      const carModel = list[0]
      if (!carModel) {
        return
      }
      const isMore = carModel.useNum >= carModel.stockNum
      if (isMore) {
        Modal.confirm({
          title: '提示',
          simple: true,
          cancelText: '取消',
          okText: '确认',
          width: '480px',
          content: h('div', null, [
            h('p', null, `订单周期为: ${orderInfo.startTime}-${orderInfo.endTime}`),
            h('p', null, `您选择的车型已超卖`),
            h('p', null, `请确认是否选择此车型？`),
          ]),
          onOk: () => {
            emit('confirm', carModelStockState.selector.id, carModel)
            close()
          },
        })
        return
      }
      emit('confirm', carModelStockState.selector.id, carModel)
      close()
    })
  }

  // 加载数据
  // loading状态
  const initLoading = ref(true)
  const listLoading = ref(false)
  let lastSiteId = undefined as any
  const loadData = () => {
    listLoading.value = true
    const query = carModelStockState.queryParam
    if (!query.siteId) {
      query.siteId = lastSiteId
    }
    lastSiteId = query.siteId

    query.startTime = dayjs(query.dateRange[0]).format('YYYY-MM-DD 00:00:00')
    query.endTime = dayjs(query.dateRange[1]).format('YYYY-MM-DD 23:59:59')
    carModelStockState.stockData = []
    getCarModelStock(query).then((res: any) => {
      if (initLoading.value) {
        setTimeout(() => {
          initLoading.value = false
        }, 400)
      }
      listLoading.value = false
      carModelStockState.stockData = res.result.list
      carModelStockState.statistics = res.result.statistics
    })
  }
</script>
